#include "stdlib.h"
#include "stdio.h"

char* currentDir = NULL;

void memset(char* src,char value,unsigned long count){


    while(count--)
    {
        *src =  value;
        src++;
    }

}


int cd_command(int argc,char** argv){};
int ls_command(int argc,char** argv){};
int pwd_command(int argc,char** argv){

    if(currentDir)
        printf("%s\n",currentDir);

}

int cat_command(int argc,char** argv){};
int touch_command(int argc,char** argv){};
int rm_command(int argc,char** argv){};
int mkdir_command(int argc,char** argv){};
int rmdir_command(int argc,char** argv){};
int exec_command(int argc,char** argv){};
int reboot_command(int argc,char** argv){

    reboot(SYSTEM_REBOOT,NULL);

};



struct	buildincmd shell_internal_cmd[] = 
{
	{"cd",cd_command},
	{"ls",ls_command},
	{"pwd",pwd_command},
	{"cat",cat_command},
	{"touch",touch_command},
	{"rm",rm_command},
	{"mkdir",mkdir_command},
	{"rmdir",rmdir_command},
	{"exec",exec_command},
	{"reboot",reboot_command},
};


int parseCommand(char* buf,int* argc,char*** argv)
{
    int i = 0;
    int j = 0;
    while(buf == ' ')
        j++;
    for(i = j; i < 256;i++){

        if(!buf[i])
            break;
        if(buf[i] != ' ' && (buf[i + 1] == ' ' || buf[i + 1] == '\0'))
            (*argc)++;

    }


    if(!*argc)
        return -1;
    *argv = (char**)malloc(sizeof(char**) * (*argc));
 
   
    for (    i = 0; i < *argc && j < 256; i++)
    {

        *((*argv) + i) = &buf[j];

        while (buf[j] && buf[j] != ' ')
        {
            j++;
        }

        while(buf[j] == ' ')
            j++;

        // printf("%s\n",(*argv)[i]);

    }
    
    return findCmd(**argv);
}






int findCmd(char* cmd)
{
    int i = 0;
	for(i = 0;i<sizeof(shell_internal_cmd)/sizeof(struct buildincmd);i++)
		if(!strcmp(cmd,shell_internal_cmd[i].name))
			return i;
	return -1;
}


void run_command(int index,int argc,char **argv)
{
	// printf("run_command %s\n",shell_internal_cmd[index].name);
	shell_internal_cmd[index].function(argc,argv);
}